package com.jinmei.remote.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import com.jinmei.remote.request.BaseClientRequest;
import com.jinmei.remote.response.JSONResponse;
import com.jinmei.remote.response.ResponseFactory;
import com.jinmei.remote.util.RequestUtils;

public class URLConnectionClient implements JHttpClient {

    public <T extends JSONResponse> T execute(BaseClientRequest request, Map<String, String> headers,
                                                     String requestMethod, Class<T> responseClass)
        throws Exception {

        String responseBody = null;
        URLConnection c = null;
        int responseCode = 0;
        try {
            URL url = new URL(request.getLocationUri());

            c = url.openConnection();
            responseCode = -1;
            if (c instanceof HttpURLConnection) {
                HttpURLConnection httpURLConnection = (HttpURLConnection)c;

                if (headers != null && !headers.isEmpty()) {
                    for (Map.Entry<String, String> header : headers.entrySet()) {
                        httpURLConnection.addRequestProperty(header.getKey(), header.getValue());
                    }
                }

                if (!RequestUtils.isEmpty(requestMethod)) {
                    httpURLConnection.setRequestMethod(requestMethod);
                    if (requestMethod.equals(RequestUtils.HttpMethod.POST)) {
                        httpURLConnection.setDoOutput(true);
                        OutputStream ost = httpURLConnection.getOutputStream();
                        PrintWriter pw = new PrintWriter(ost);
                        pw.print(request.getBody());
                        pw.flush();
                        pw.close();
                    }
                } else {
                    httpURLConnection.setRequestMethod(RequestUtils.HttpMethod.GET);
                }

                httpURLConnection.connect();

                InputStream inputStream;
                responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 400) {
                    inputStream = httpURLConnection.getErrorStream();
                } else {
                    inputStream = httpURLConnection.getInputStream();
                }

                responseBody = saveStreamAsString(inputStream);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return ResponseFactory
            .createCustomResponse(responseBody, c.getContentType(), responseCode, responseClass);
    }

	/**
	 * you may override this method by replacing saveStreamAsUTF8 as saveStreamAsGBK
	 * for specail case of reading inputstream of GBK charset.
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	protected String saveStreamAsString(InputStream inputStream) 
			throws IOException {
		return RequestUtils.saveStreamAsUTF8(inputStream);
	}

}
